<template>
  <div class="app-container search-list-container poll">
    <div class="search-wrapper">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="auto"
      >
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input
            v-model="queryParams.messageTitle"
            placeholder="请输入消息标题"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select
            clearable
            v-model="queryParams.messageType"
            placeholder="请选择"
          >
            <el-option
              v-for="item in messageTypeData"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送方式" prop="messageMethod">
          <el-select
            clearable
            v-model="queryParams.messageMethod"
            placeholder="请选择"
          >
            <el-option
              v-for="item in messageMethodData"
              :key="item.lable"
              :label="item.lable"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="expireDate">
          <el-date-picker
            size="small"
            v-model="queryParams.expireDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </div>
      </el-form>
    </div>
    <div class="list-wrapper">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:message:send']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            :disabled="multiple"
            v-hasPermi="['system:message:delete']"
            >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:message:export']"
            >导出</el-button
          >
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <el-table
        v-loading="loading"
        :data="infoList"
        height="100%"
        width="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="消息标题"
          align="center"
          prop="messageTitle"
          :render-header="renderHeader"
          show-overflow-tooltip
        />
        <el-table-column
          label="消息内容"
          align="center"
          prop="messageContext"
          :render-header="renderHeader"
          show-overflow-tooltip
        />

        <el-table-column
          label="消息类型"
          align="center"
          prop="messageTypeToString"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="发送方式"
          align="center"
          prop="messageMethod"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.messageMethod == 1 ? "定时发送" : "立即发送" }}
          </template>
        </el-table-column>
        <el-table-column
          label="发送状态"
          align="center"
          prop="sendStatus"
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span
              class="text-status"
              :class="{
                green: scope.row.sendStatus == 1,
                red: scope.row.sendStatus == 0,
              }"
              >{{ scope.row.sendStatus == 1 ? "已发送" : "未发送" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="已读人数"
          align="center"
          prop="readCounts"
          :render-header="renderHeader"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :render-header="renderHeader"
          show-overflow-tooltip
        />
        <el-table-column
          label="发送时间"
          align="center"
          prop="expireDate "
          :render-header="renderHeader"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.delayTime ? scope.row.delayTime : scope.row.createTime
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
              v-hasPermi="['system:message:detail']"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getList"
      />
    </div>
    <!-- 新增 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      :class="juBge ? 'frame-detail' : 'frame-edit'"
      @close="closeAdd"
    >
      <el-form
        ref="form"
        :disabled="juBge"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="消息标题" prop="messageTitle">
          <el-input
            v-model="addForm.messageTitle"
            placeholder="请输入消息标题"
          />
        </el-form-item>
        <el-row>
          <el-col :span="14">
            <el-form-item label="发送方式" prop="messageMethod">
              <el-radio-group
                v-model="addForm.messageMethod"
                @change="changeRadio"
              >
                <el-radio :label="0">立即发送</el-radio>
                <el-radio :label="1">定时发送</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              v-if="showTimePick"
              class="delayTimeContent"
              prop="delayTime"
            >
              <el-date-picker
                v-model="addForm.delayTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                class="delayTimeStyle"
                popper-class="delayTimeStyles"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="消息接收者" prop="userIdListToString">
          <el-input
            v-model="addForm.userIdListToString"
            @focus="openChoiceUser = true"
            placeholder="请选择消息接收者"
            readonly
          />
        </el-form-item>
        <el-form-item label="消息内容" prop="messageContext">
          <el-input
            type="textarea"
            placeholder="请输入消息内容"
            v-model="addForm.messageContext"
            maxlength="1000"
            show-word-limit
            :rows="8"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog
      :title="title"
      :visible.sync="openCheck"
      width="600px"
      :class="juBge ? 'frame-detail' : 'frame-edit'"
    >
      <div style="font-size: 16px">{{ form.messageTitle }}</div>
      <div style="margin: 20px 0px 20px 20px">
        <span style="width: 40px"></span>{{ form.messageContext }}
      </div>
      <div style="text-align: right">时间：{{ form.createTime }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openCheck = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择发送人员 -->
    <el-dialog
      title="消息接收者"
      :visible.sync="openChoiceUser"
      width="80%"
      class="frame-edit"
      v-loading="loadingDialog"
    >
      <div class="transferStyle">
        <div class="el-transfer-panel">
          <p class="el-transfer-panel__header">
            <span style="color: #fff; font-size: 16px">人员选择</span>
          </p>
          <div class="el-transfer-panel__body">
            <el-tree
              :data="deptOptions"
              :props="deptOptionsProps"
              :expand-on-click-node="false"
              ref="tree"
              node-key="label"
              show-checkbox
              @check="handleNodeClick"
            />
          </div>
        </div>
        <el-transfer
          v-model="addForm.userIdList"
          :data="transferData"
          :titles="['人员列表', '已选人员']"
          class="transferChose"
          @change="changeTransfer"
        ></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openChoiceUserCom">确 定</el-button>
        <el-button @click="openChoiceUserClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  addInfo,
  listUser,
  addInfoDelay,
  deleteMessage,
} from "@/api/insideMessage/management";
import { treeselect } from "@/api/system/dept";

export default {
  name: "Info",
  inject: ["reload"],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      juBge: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 终端鉴权白名单表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        messageTitle: null,
        messageType: null,
        expireDate: null,
        messageMethod: null,
        createId: window.localStorage.getItem("userId"),
      },
      // 查询参数
      addForm: {
        messageTitle: null,
        delayTime: null,
        messageMethod: 0,
        userIdList: [],
        userIdListToString: null,
        messageContext: null,
        messageType: 1,
      },
      userIdListToString: "",
      messageTypeData: [
        {
          lable: "系统消息",
          value: 0,
        },
        {
          lable: "通知公告",
          value: 1,
        },
        {
          lable: "告警消息",
          value: 2,
        },
      ],
      messageMethodData: [
        {
          lable: "立即发送",
          value: 0,
        },
        {
          lable: "定时发送",
          value: 1,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        messageTitle: [
          { required: true, message: "请输入消息标题", trigger: "blur" },
        ],
        messageMethod: [
          { required: true, message: "请选择发送方式", trigger: "change" },
        ],
        messageContext: [
          {
            required: true,
            message: "请输入消息内容",
            trigger: ["blur", "change"],
          },
        ],
        userIdListToString: [
          {
            required: true,
            message: "请选择消息接收者",
            trigger: ["blur", "change"],
          },
        ],
        delayTime: [
          {
            required: true,
            message: "请选择日期时间",
            trigger: "change",
          },
        ],
      },
      openCheck: false,
      showTimePick: false,
      openChoiceUser: false,
      transferData: [],
      deptOptionsProps: {
        children: "children",
        label: "label",
      },
      deptOptions: [],
      loadingDialog: false,
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    handleExport() {
      this.download(
        "/inifrastructure/message/messageExport",
        {
          ...this.queryInfo,
        },
        `messages_${new Date().getTime()}.xlsx`
      );
    },
    getList() {
      this.loading = true;
      if (this.queryParams.expireDate) {
        this.queryParams.startTime =
          this.queryParams.expireDate[0] + " 00:00:00";
        this.queryParams.endTime = this.queryParams.expireDate[1] + " 23:59:59";
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询单位名称下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    // 节点选择事件
    handleNodeClick(data, value) {
      this.loadingDialog = true;
      this.transferData = [];
      let depIds = [];
      if (value.checkedNodes) {
        value.checkedNodes.forEach((item) => {
          depIds.push(item.id);
        });
      }
      let obj = {
        deptIds: depIds,
      };
      listUser(obj).then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            this.transferData.push({
              key: item.userId,
              label: item.userName,
            });
          });
          this.loadingDialog = false;
        }
      });
    },
    //穿梭框发生变化
    changeTransfer() {},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.queryParams = {
        idCode: null,
        deivceName: null,
        macAddress: null,
        ipAddress: null,
        expireDate: null,
        entitlementUnit: null,
        createId: window.localStorage.getItem("userId"),
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.juBge = false;
      this.open = true;
      this.title = "新增消息";
    },
    handleDelete() {
      const ids = this.ids;
      this.$modal
        .confirm("是否确认删除所选的" + ids.length + "个数据项？")
        .then(function () {
          return deleteMessage(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    changeRadio(value) {
      this.$set(this.form, "messageMethod", value);
      if (value == 1) {
        this.showTimePick = true;
      } else {
        this.showTimePick = false;
      }
    },
    /** 查看 */
    handleSee(row) {
      this.juBge = true;
      const id = row.id;
      getInfo({ messageId: id }).then((response) => {
        this.form = response.data;
        this.openCheck = true;
        this.$store.dispatch("insideMessage/changeIsDot");
        this.title = "消息详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.addForm.messageMethod == 1) {
            this.$store
              .dispatch("insideMessage/addInfoDelayMessage", this.addForm)
              .then((res) => {
                this.$store.dispatch("insideMessage/isReadCounts", {
                  userId: localStorage.getItem("userId"),
                });
                this.open = false;
                this.$modal.msgSuccess("新增成功");
                this.getList();
              });
          } else {
            this.$store
              .dispatch("insideMessage/addInfoMessage", this.addForm)
              .then((res) => {
                this.$store.dispatch("insideMessage/isReadCounts", {
                  userId: localStorage.getItem("userId"),
                });
                this.open = false;
                this.$modal.msgSuccess("新增成功");
                this.getList();
              });
          }
        }
      });
    },
    closeAdd() {
      this.reset();
      this.transferData=[];
      this.addForm.userIdList=[];
      this.$refs.tree?.setCheckedNodes([])
      // this.reload();
    },
    openChoiceUserCom() {
      let arr = [];
      this.addForm.userIdList.forEach((item) => {
        this.transferData.forEach((ele) => {
          if (ele.key == item) {
            arr.push(ele.label);
          }
        });
      });
      this.addForm.userIdListToString = arr.join(",");
      this.openChoiceUser = false;
    },
    openChoiceUserClose() {
      this.openChoiceUser = false;
    },
    renderHeader(h, { column, $index }) {
      // 新建一个 span
      let span = document.createElement("span");
      // 设置表头名称
      span.innerText = column.label;
      // 临时插入 document
      document.body.appendChild(span);
      column.minWidth = span.getBoundingClientRect().width + 20;
      // 移除 document 中临时的 span
      document.body.removeChild(span);
      return h("span", column.label);
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/assets/styles/system.scss";
// .poll .frame-edit .el-cascader--medium{
//   width: 100% !important;
// }
// .poll .frame-edit .el-select--medium{
//   width: 100% !important;
// }
.delayTimeContent {
  ::v-deep .el-form-item__content {
    margin-left: 0 !important;
  }
}
.delayTimeStyle {
  width: 94% !important;
  margin-left: 5%;
}
::v-deep.el-textarea .el-input__count {
  background: #04264e;
  color: #fff;
}
::v-deep .el-transfer-panel {
  background: unset;
}
.transferStyle {
  display: flex;
  justify-content: space-between;
  .transferChose {
    width: 72%;
    ::v-deep .el-transfer-panel {
      width: 38%;
      background: unset;
    }
  }
  ::v-deep .el-transfer-panel {
    width: 25%;
    .el-transfer-panel__body {
      overflow: auto;
    }
  }
  ::v-deep .el-transfer-panel__body {
    background: #04264e;
  }
  ::v-deep .el-transfer__buttons {
    padding: 0 10px;
  }
}
</style>
